package cn._2dland.leech.clients;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;

import cn._2dland.leech.LeechClient;

/**
 * A leech client use www.linktopremium.com
 * @author deadblue
 */
public class LTPClient extends LeechClient {

	@Override
	protected boolean needLogin() {
		return true;
	}

	@Override
	protected void login() throws Exception {
		GetMethod get = new GetMethod("http://www.linktopremium.com/index.php");
		try {
			int respCode = client.executeMethod(get);
			if(respCode != HttpStatus.SC_OK) throw new Exception("HTTP Error: " + respCode);
		} finally {
			get.releaseConnection();
		}
	}

	@Override
	protected String getParseURL(String url) {
		return "http://www.linktopremium.com/index.php";
	}

	@Override
	protected String getParseReferer(String url) {
		return "http://www.linktopremium.com/";
	}

	@Override
	protected NameValuePair[] getParseParams(String url) {
		NameValuePair[] params = {
				new NameValuePair("link", url),
				new NameValuePair("submit.x", "43"),
				new NameValuePair("submit.y", "11"),
				new NameValuePair("iuser", ""),
				new NameValuePair("ipass", ""),
				new NameValuePair("comment", ""),
				new NameValuePair("yt_fmt", "highest"),
				new NameValuePair("tor_user", ""),
				new NameValuePair("tor_pass", ""),
				new NameValuePair("mu_cookie", ""),
				new NameValuePair("cookie", ""),
				new NameValuePair("email", ""),
				new NameValuePair("method", "tc"),
				new NameValuePair("partSize", "10"),
				new NameValuePair("proxy", ""),
				new NameValuePair("proxyuser", ""),
				new NameValuePair("proxypass", ""),
				new NameValuePair("premium_acc", "on"),
				new NameValuePair("premium_user", ""),
				new NameValuePair("premium_pass", ""),
				new NameValuePair("path", "/home/linkto/public_html/files")
		};
		return params;
	}

	@Override
	protected String getTransloadURL(String url) {
		return "http://www.linktopremium.com/index.php";
	}

	@Override
	protected String parseDownloadURL(String url, String body) {
		String downURL = null;

		Matcher m = Pattern.compile("<a href=\"/files/[^\"]+\"").matcher(body);
		if(m.find()) {
			downURL = body.substring(m.start() + 9, m.end() - 1);
			downURL = "http://www.linktopremium.com" + downURL;
		}

		return downURL;
	}

}
